<template>
    <div class="">
        <Breadcrumb :route="routes" />
         <div class="wb-container">
            <div class="mian-content">
                <div class="header-content">
                    <div>
                        <el-button type="primary" @click="loadingClick" style="margin-right: 10px;">
                            <el-icon>
                                <Loading />
                            </el-icon>
                        </el-button>
                        <router-link to="/goodsAdd">
                            <el-button type="primary" v-has="'visionGoodsAdd'">
                                添加商品
                            </el-button>
                        </router-link>
                        <el-button type="danger" :disabled="disabledRemove" @click="allRemove" style="margin-left: 10px;">
                            删除
                        </el-button>
                    </div>
                    <div>
                        <div class="searchbox">
                            <el-form :inline="true" :model="list.searchForm">
                                <el-form-item>
                                    <el-select v-model="list.searchForm.goods_cate_id" placeholder="商品分类"
                                        @change="SelectChange">
                                        <el-option v-for="item in list.cateList" :key="item.id" :label="item.name"
                                            :value="item.id" class="selectstyle" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item>
                                    <el-input v-model="list.searchForm.name" placeholder="商品名称" />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="getGoodsList">搜索</el-button>
                                    <el-button type="primary" @click="searchRemove">重置</el-button>
                                    <el-button type="success" @click="getExcelList"
                                        v-has="'visionGoodsExport'">导出商品</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </div>
                <el-table ref="tableRef" v-loading="loading" element-loading-text="加载数据..." :data="list.goods" border
                    style="width: 100%;height: 100%;"
                    :header-cell-style="{ background: '#44abf7', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }"
                    @select="selectClick" @select-all="selectAll" @selection-change="seleChange" stripe size="small">
                    <template #empty>
                        <el-empty description="暂无数据！" />
                    </template>
                    <el-table-column type="selection" align="center" width="50" />
                    <!-- <el-table-column prop="admin_user_id" label="管理员ID" width="100" align="center" fixed /> -->
                    <el-table-column prop="name" label="商品名称" width="200" align="center" fixed>
                        <template #default="{ row }">
                            <el-input v-show="row.showmode" v-model="row.name" style="width:160px"></el-input>
                            <div v-show="!row.showmode">{{ row.name }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="admin_user.account" label="商户名称" width="160" align="center" />
                    <el-table-column prop="unit" label="单位" width="100" align="center" />
                    <el-table-column prop="image" label="图片" width="140" align="center">
                        <template #default="scope">
                            <div class="orderImg">
                                <el-image :src="scope.row.image" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="价格" width="120" align="center">
                        <template #default="{ row }">
                            <el-input v-show="row.showmode" v-model="row.price" style="width:80px"></el-input>
                            <div v-show="!row.showmode">￥{{ row.price }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="商品类型" width="140" align="center">
                        <template #default="{ row }">
                            <el-tag v-if="row.type == 1">称重商品</el-tag>
                            <el-tag v-if="row.type == 2">视觉商品</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="140" align="center">
                        <template #default="{ row }">
                            <el-tag v-if="row.status == 1">上架</el-tag>
                            <el-tag type="warning" v-if="row.status == 2">下架</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" width="160" align="center">
                        <template #default="{ row }">
                            <el-input v-show="row.showmode" v-model="row.stock" style="width:100px"></el-input>
                            <div v-show="!row.showmode">
                                <div v-if="row.stock != null">{{ row.stock }}</div>
                                <div v-show="row.stock == null">0</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="address" label="操作" min-width="300" align="center" fixed="right">
                        <template #default="scope2">
                            <span v-show="!scope2.row.showbtn">
                                <el-button type="primary" @click="clickEdit(scope2)">修改</el-button>
                            </span>
                            <span v-show="scope2.row.showbtn">
                                <el-button type="danger" @click="saveClick(scope2.row)">保存</el-button>
                                <el-button type="warning" @click="clickEditBl(scope2)">取消</el-button>
                            </span>
                            <el-button style="background-color: #95d475;" v-if="isBusiness" @click="editClcik(scope2.row)"
                                v-has="'visionGoodsEdit'">编辑</el-button>
                            <el-button style="background-color: #D4D7DE;" @click="DetaliClick(scope2.row)"
                                v-has="'visionGoodsDetali'">详情</el-button>
                            <el-button style="background-color: #f56c6c;" @click="removeClick(scope2.row)"
                                v-has="'visionGoodsRemove'">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[15, 20, 25, 30]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
            <el-dialog v-model="dialogFormVisible" title="商品详情" width="30%" center>
                <el-form :model="list.form" :label-width="120">
                    <el-form-item label="商品名称：">
                        <span>{{ list.form.name }}</span>
                    </el-form-item>
                    <el-form-item label="商品图片：">
                        <el-image :src="list.form.image" style="width:100px;height: 100px;"></el-image>
                    </el-form-item>
                    <el-form-item label="商品单价：">
                        <span>{{ list.form.price }}元</span>
                    </el-form-item>
                    <el-form-item label="出厂价：">
                        <span>{{ list.form.cost_price }}元</span>
                    </el-form-item>
                    <el-form-item label="商品库存：">
                        <span v-if="list.form.stock != null">{{ list.form.stock }}个</span>
                        <span v-if="list.form.stock == null">0 个</span>
                    </el-form-item>
                    <el-form-item label="是否上架" style="align-items: center;">
                        <el-radio-group v-model="list.form.status" class="ml-4">
                            <el-radio label="1" size="large">上架</el-radio>
                            <el-radio label="2" size="large">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import Breadcrumb from '@/components/nav-header'
import { goodsList, goodsDetali, goodsRemove, goodsEdit } from '@/api/goods'
import { goodsCateList } from '@/api/GoodsCate'
import { changeTableHead } from '@/utlis/index'
import * as xlsx from 'xlsx'
import { useRouter } from 'vue-router'
import { ElMessage } from "element-plus";
import store from "@/store";
const route = useRoute()
const routes = ref()
const router = useRouter()
const list = reactive({
    goods: [],
    searchForm: {
        goods_cate_id: '',
        name: ''

    },
    form: {},
    cateList: [],
    select_goods: [],
    searchData: []
})
const currentPage = ref(1)
const pageSize = ref(15)
const small = ref(true)
const background = ref(true)
const disabled = ref(false)
const disabledRemove = ref(true)
const total = ref(0)
const loading = ref(true)
const dialogFormVisible = ref(false)
const tbsts = ref()
const isBusiness = ref(false)

onMounted(() => {
    routes.value = route.matched
    getGoodsList()
    getGoodsCate()
    let roleNmae = JSON.parse(store.state.UserInfo)
    if (roleNmae.role_name.includes('BOSS')) {
        isBusiness.value = true
    }
})
const getGoodsList = async () => {
    const res = await goodsList(list.searchForm).then(res => {
        const { code, data } = res
        loading.value = false
        if (code == 200) {
            list.goods = data.data
            total.value = data.total
        }
    }).catch((err) => {
        loading.value = false
    })
}
const editClcik = (row) => {
    let editList = JSON.parse(JSON.stringify(row))
    router.push({
        name: 'goodsAdd',
        state: { editList }
    })
}
const DetaliClick = async (row) => {
    dialogFormVisible.value = true
    const DetaliData = await goodsDetali(row.id).then(r => {
        const { code, data } = r
        if (code == 200) {
            list.form = data
            list.form.status = String(data.status)
        }
    })
}
const goodsDelete = async (delId) => {
    const removeGoodslist = await goodsRemove(delId).then(s => {
        const { code, data } = s
        if (code == 200) {
            getGoodsList()
            ElMessage({
                type: 'success',
                message: '商品删除成功',
            })
        }
    })
}
const removeClick = (row) => {
    ElMessageBox.confirm(
        '确定要删除这条商品数据吗？',
        '删除商品数据',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let removeId = row.id
            goodsDelete(removeId)
        })
        .catch(() => {

        })
}
const clickEdit = (scope1) => {
    tbsts.value = 'xg'
    btngroupChange(tbsts.value, scope1)
}
function btngroupChange(tbstsvalue, scope1) {
    if (tbstsvalue == "xg") {
        scope1.row.showmode = true
        scope1.row.showbtn = true
    } else if (tbstsvalue == "fxg") {
        scope1.row.showmode = false
        scope1.row.showbtn = false
    }
}
const clickEditBl = (scope1) => {
    scope1.row.showmode = false
    scope1.row.showbtn = false
}
const saveClick = async (row) => {
    let editGoods = {}
    editGoods.name = row.name
    editGoods.price = row.price
    editGoods.stock = Number(row.stock)
    editGoods.type = 2
    await goodsEdit(row.id, editGoods).then(ress => {
        const { code, data } = ress
        if (code == 200) {
            ElMessage.success('编辑成功')
            row.showmode = false
            row.showbtn = false
        }
    })
}
const searchRemove = () => {
    list.searchForm.goods_cate_id = ''
    list.searchForm.admin_user_id = ''
    list.searchForm.name = ''
    getGoodsList()
}
const getGoodsCate = async () => {
    const cate = await goodsCateList().then(res => {
        const { code, data } = res
        if (code == 200) {
            list.cateList = data.data
        }
    })
}
const allRemove = () => {
    for (let i = 0; i < list.select_goods.length; i++) {
        try {
            simulation(list.select_goods[i])
        } catch (err) {
            // console.log(err);
        }
    }
}
const simulation = async (select) => {
    await goodsRemove(select.id).then(res => {
        const { code, data } = res
        if (code == 200) {
            getGoodsList()
        }
    })
}
const handleSizeChange = (val) => {
    pageSize.value = val
    list.searchForm.limit = pageSize.value
    getGoodsList(list.searchForm)
}
const handleCurrentChange = (value) => {
    currentPage.value = value
    list.searchForm.page = currentPage.value
    getGoodsList(list.searchForm)
}
const SelectChange = (val) => {
    list.searchForm.goods_cate_id = val
}
const selectClick = (data) => {
    list.select_goods = data
}
const selectAll = (val) => {
    list.select_goods = val
}
const seleChange = (sele) => {
    if (Array.isArray(sele) && sele.length) {
        disabledRemove.value = false
    } else {
        disabledRemove.value = true
    }
}
const loadingClick = () => {
    getGoodsList()
    getGoodsCate()
}
const getExcelList = async () => {
    list.searchForm.limit = total.value
    await goodsList(list.searchForm).then(res => {
        const { code, data } = res
        if (code == 200) {
            list.searchData = data.data
        }
    })
    let firstName = {
        name: '商品名称',
        price: '商品价格',
        stock: '商品库存',
        image: '商品图片',
        unit: '单位',
        weight: '重量',
        lable: '标签',
        cost_price: '成本价'
    }
    let goodsExcelData = changeTableHead(list.searchData, firstName)
    const data = xlsx.utils.json_to_sheet(goodsExcelData);
    const wb = xlsx.utils.book_new();
    data['!cols'] = [{
        wpx: 200
    }, {
        wpx: 100
    },
    {
        wpx: 500
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    ]
    let goodsListName = '商品列表'
    let fileName = 'Sheet1'
    xlsx.utils.book_append_sheet(wb, data, goodsListName);
    xlsx.writeFile(wb, `${fileName}.xlsx`);
    list.searchForm.limit = pageSize.value
    getGoodsList()
}
</script>

<style lang="less" scoped>
.page-toolbar {
    position: relative;
    width: 100%;
    padding: 20px 0;
    line-height: 1;
    vertical-align: middle;
    margin-bottom: 15px;
    background: #fff;

    .pull-left {
        display: flex;
        margin-right: 30px;

        .right {
            margin-right: 4px;
        }
    }

    .btn {
        outline: none !important;
        padding: 8px 16px;
        border-radius: 2px;
        font-size: 12px;
        line-height: 1;
        color: #fff;
        text-align: center;
        vertical-align: middle;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        cursor: pointer;
        -webkit-transition: background-color 0.3s;
        -moz-transition: background-color 0.3s;
        transition: background-color 0.3s;
        border: 1px solid transparent;
    }

    .btn-primary {
        background: #44abf7 !important;
        border-color: #44abf7 !important;
        color: #fff !important;
    }

    .btn-success {
        background: #54c952 !important;
        border-color: #54c952 !important;
        color: #fff !important;
        margin-left: 0;
    }

    .btn-sm {
        display: inline-block;
        padding: 7px 8px;
        border-radius: 2px;
        font-size: 12px;
        line-height: 1;
        color: #fff;
        background: #dddddd;
        text-align: center;
        vertical-align: middle;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        cursor: pointer;
        -webkit-transition: background-color 0.3s;
        -moz-transition: background-color 0.3s;
        transition: background-color 0.3s;
    }

    .input-group {
        position: relative;
        display: flex;
        border-collapse: separate;

        .input-sm {
            height: 30px;
            padding: 5px 10px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 3px;
        }

        .form-control {
            display: block;
            height: 32px;
            padding: 6px 12px;
            font-size: 14px;
            line-height: 1.42857143;
            color: #555;
            background-color: #fff;
            background-image: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
            -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
            -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
            transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
        }

        .input-group-btn {
            position: relative;
            font-size: 0;
            white-space: nowrap;
            width: 1%;
            white-space: nowrap;
            vertical-align: middle;
            display: flex;
        }
    }
}

.header-content {
    width: 100%;
    background-color: #fff;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
}

.searchbox {
    display: flex;
}

.inpbox {
    display: flex;
}

.el-table span {
    padding: 10px;
}

span:hover {
    cursor: pointer;
}

.demo-pagination-block {
    margin-top: 20px;
}

.selectstyle:hover {
    background-color: #409eff;
    color: #fff;
}

:deep(.el-dialog .el-dialog__body) {
    border-top: 1px solid #efefef;
}

:deep(.el-button) {
    padding: 2px 6px;
    letter-spacing: 2px;
    font-size: 12px;
    color: #fff;
}

.btn {
    color: #fff;
    border-radius: 10px;
}

.commodity-btn {
    margin-bottom: 20px;
}

.orderImg {
    display: flex;
    justify-content: center;
    align-items: center;

    .el-image {
        width: 60px;
        height: 60px;
        margin: 10px 0;
    }
}
</style>

